package utils

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func Get(url string) ([]byte, error) {
	//发送请求获取响应
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	//结束网络释放资源
	if resp != nil {
		defer resp.Body.Close()
	}
	//判断响应状态码
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New(fmt.Sprintf("response status code %v", resp.StatusCode))
	}

	//读取响应实体
	bs, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return bs, nil
}

func Post(url string, params url.Values, contentType string) ([]byte, error) {

	body := strings.NewReader(params.Encode())

	if contentType == "" {
		contentType = "application/x-www-form-urlencoded"
	}

	resp, err := http.Post(url, contentType, body)
	if err != nil {
		return nil, err
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New(fmt.Sprintf("response status code %v", resp.StatusCode))
	}

	bs, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return bs, nil
}
